/* eslint-disable no-undef */
<!--
/**
* @name OperateForm
* @description ** 新增编辑用户
* @author mdong
* @date 2020-05-12
* @param {**} ** **
* @example ***
*/
-->
<template>
  <div calss="operate-form-enterpriseInformation">
    <form-loading :formLoadingVisible="formLoadingVisible"></form-loading>
    <h3 class="form-title">基本信息</h3>
    <a-form-model ref="ruleForm"
                  class="custom-form-item-bottom"
                  :hideRequiredMark="optType === 'view'"
                  :model="form"
                  :rules="rules"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-model-item label="企业名称"
                             prop="name">
            <span v-if=" optType ==='view' ">{{form.name}} </span>
            <a-input v-else
                     allowClear
                     placeholder="请输入企业名称"
                     v-model="form.name"
                     :maxLength="50">
            </a-input>

          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="社会信用代码"
                             prop="custUniformCode">
            <span v-if=" optType === 'view' ">{{form.custUniformCode}} </span>
            <a-input v-else
                     allowClear
                     placeholder="请输入社会信用代码"
                     v-model="form.custUniformCode"
                     :maxLength="18">
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- form.provinceCode form.cityCode form.areaCode form.planCode-->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-model-item label="所在区域"
                             prop="areaList">
            <span v-show="optType ==='view'">{{form.province}}{{form.city}}{{form.area}}{{form.areaList.length >= 4? form.planTownship: ''}} </span>
            <a-cascader v-show="optType !=='view'"
                        v-model="form.areaList"
                        :allowClear="false"
                        :showSearch="true"
                        :options="areaConst"
                        :field-names="{ label: 'title', value: 'key', children: 'children' }"
                        expand-trigger="hover"
                        placeholder="请选择行政区域"
                        @change="areaChange" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="重点监管企业"
                             prop="type">
            <span v-if=" optType ==='view' " style="white-space:nowrap;">{{form.type === '1'? '是': (form.type === '0'? '否': '无')}} </span>
             <a-select v-else
                      v-model="form.type"
                      style="width: 100%"
                      placeholder="请选择重点监管企业"
                      allowClear>
              <a-select-option key="1"
                               value="1">是</a-select-option>
              <a-select-option key="0"
                               value="0">否</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-model-item label="联系人"
                             prop="contacts">
            <span v-if=" optType ==='view' ">{{form.contacts}} </span>
            <a-input v-else
                     allowClear
                     v-model="form.contacts"
                     placeholder="请输入联系人"
                     :maxLength="15">
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="联系电话"
                             prop="contactsPhone">
            <span v-if=" optType ==='view' ">{{form.contactsPhone}} </span>
            <a-input v-else
                     allowClear
                     placeholder="请输入联系电话"
                     v-model="form.contactsPhone"
                     :maxLength="13">
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-model-item label="数据来源">
            <span v-if=" optType ==='view' ">{{convertConstName(dataSourcesConst,form.sources)}} </span>
            <a-select v-model="form.sources"
                      v-else
                      style="width: 100%"
                      placeholder="请选择数据来源"
                      allowClear>
              <a-select-option v-for="(item,index) in  dataSourcesConst "
                               :key="index"
                               :value="item.value"> {{item.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="企业环保分类">
            <span v-if=" optType ==='view' ">{{convertConstName(environmentalProtectionConst,form.protectionType)}} </span>
            <a-select v-model="form.protectionType"
                      v-else
                      style="width: 100%"
                      placeholder="请选择环保分类"
                      allowClear>
              <a-select-option v-for="(item,index) in  environmentalProtectionConst "
                               :key="index"
                               :value="item.value"> {{item.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-model-item label="产业类型"
                             prop="industryTypeCode">
            <span v-if=" optType ==='view' ">{{ convertConstName(industryTypeConst,form.industryTypeCode)}} </span>
            <a-select v-else
                      v-model="form.industryTypeCode"
                      style="width: 100%"
                      placeholder="请选择产业类型"
                      allowClear>
              <a-select-option v-for="(item,index) in  industryTypeConst "
                               :key="index"
                               :value="item.value"> {{item.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="行业大类"
                             prop="industryCategoryMaxCode">
            <span v-if=" optType ==='view' ">{{convertConstName(industryBigCategoryConst,form.industryCategoryMaxCode)}} </span>
            <a-select v-else
                      v-model="form.industryCategoryMaxCode"
                      style="width: 100%"
                      placeholder="请选择行业大类"
                      allowClear>
              <a-select-option v-for="(item,index) in  industryBigCategoryConst "
                               :key="index"
                               :value="item.value"> {{item.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-model-item label="国民经济分类"
                             prop="industryCategoryName">
            <span v-if=" optType ==='view' ">{{ industryCategoryName}} </span>
            <a-input v-else
                     allowClear
                     @click="openModalTree"
                     ref="industryCategoryRef"
                     placeholder="请选择国民经济分类"
                     @paste.native.capture.prevent="handlePaste"
                     v-model="industryCategoryName">
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="所属行业"
                             prop="industryCode">
            <span v-if=" optType ==='view' ">{{convertConstName(industryCategoryConst,form.industryCode)}} </span>
            <a-select v-else
                      v-model="form.industryCode"
                      style="width: 100%"
                      allowClear
                      placeholder="请选择所属行业"
                      @change="sexChange">
              <a-select-option v-for="(item,index) in industryCategoryConst "
                               :key="index"
                               :value="item.value"> {{item.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-modal title="选择国民经济分类 "
               :maskClosable="false"
               :width="800"
               wrapClassName="industryTreeModal modal-box"
               :visible="operateVisible"
               :confirm-loading="modalConfirmLoading"
               @ok="saveIndustry"
               :bodyStyle="{
                  overflowY: 'auto',
                  height: '72vh'
                }"
               @cancel="cancelSaveIndustry"
               :destroyOnClose="true">
        <a-tree :show-line="true "
                :show-icon="false"
                :tree-data="industryTreeData"
                :replace-fields="replaceFields"
                @select="selectIndustry">
        </a-tree>
      </a-modal>
      <!--标记为重点 flgStress 标记为标杆 flgAdvanced-->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-model-item label="绩效分级指标"
                             prop="indicators">
            <span v-if=" optType ==='view' ">{{convertConstName(indicatorsGradingConst,form.indicators)}} </span>
            <a-select v-else
                      v-model="form.indicators"
                      style="width: 100%"
                      placeholder="请选择绩效分级指标"
                      allowClear>
              <a-select-option v-for="(item,index) in  indicatorsGradingConst "
                               :key="index"
                               :value="item.value"> {{item.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="许可文件号"
                             prop="flieNo">
            <span v-if=" optType ==='view' ">{{form.flieNo}} </span>
            <a-input v-else
                     allowClear
                     placeholder="请输入许可文件号"
                     v-model="form.flieNo"
                     :maxLength="50">
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <h3 class="form-title">经营地址</h3>
      <a-row :gutter="16" style="align-items: center;display: flex;">
        <a-col :span="12" style="padding-left:0;padding-right:0">
          <a-col :span="24">
            <a-form-model-item  label="经营地址"
                                prop="businessAddress">
              <span v-if=" optType ==='view' "
                    style="white-space:nowrap;">{{form.businessAddress}}</span>
              <a-input v-else
                       allowClear
                       placeholder="请输入经营地址"
                       @change="getAdressByKeyWord(form.businessAddress)"
                       v-model="form.businessAddress"
                       :maxLength="50">
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item  label="经度"
                                prop="longitude">
              <span v-if=" optType ==='view' ">{{form.longitude}} </span>
              <a-input v-else
                       allowClear
                       disabled
                       placeholder="经度"
                       v-model="form.longitude"
                       :maxLength="20">
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item  label="纬度"
                                prop="latitude">
              <span v-if=" optType ==='view' ">{{form.latitude}} </span>
              <a-input v-else
                       allowClear
                       disabled
                       placeholder="纬度"
                       v-model="form.latitude"
                       :maxLength="20">
              </a-input>
            </a-form-model-item>
          </a-col>
        </a-col>
        <a-col :span="9" :offset="2">
          <a-form-model-item :labelCol="{span: 0, offset: 0}"
                             :wrapperCol="{span: 24, offset: 0}">
            <div id="mapDiv" style="height:170px"></div>
          </a-form-model-item>
        </a-col>
      </a-row>
      <h3 class="form-title">相关附件</h3>
      <a-row :gutter="16">
        <a-col :span="24">
          <!-- :wrapperCol="{span: 21, offset: 3}" -->
          <a-form-model-item  :label="optType === 'view'? '附件': '附件上传'"
                              :labelCol="{span: 3, offset: 0}"
                              prop="fileList"
                              :wrapperCol="{span: 21, offset: 0}">
            <div class="upload-list clearfix" style="height: 110px;">
              <a-upload list-type="picture-card"
                        :disabled="optType === 'view'"
                        :file-list="form.fileList"
                        @preview="handlePreview"
                        :remove="handleRemove"
                        :before-upload="beforeUpload">
                <div v-if="form.fileList.length < 5 && optType !=='view' ">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    上传
                  </div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible"
                       :footer="null"
                       @cancel="handleCancel">
                <img alt="example"
                     style="width: 100%"
                     :src="previewImage" />
              </a-modal>
            </div>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <div class="opreate-buttons">
            <a-button type="primary"
                      style="margin-right:20px"
                      v-if=" optType !=='view' "
                      :loading="confirmLoading"
                      icon="save"
                      @click="saveInfo">提交</a-button>
            <a-button @click="cancleSave" icon="close-circle">{{optType !=='view'?'取消':'关闭'}}</a-button>
          </div>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>
<script>
import { post } from '@/request/http'
import { addEntinfo, getHnEntinfoById, updateEntinfo, checkCustUniformCode, queryIndustry, getMapLonAndLatInfo } from '@/request/api/enterpriseInformationManagement/enterpriseInformation'
import { regexConstants, validators } from '@/utils/validate'
import { getDictData, getInfo } from '@/request/api/common'
import { convertConstName } from '@/utils/filter'
import { debounce } from '@/utils/debounce'
import { Tree, Cascader, FormModel, Upload, Modal, Icon, Row, Col, Input, Select, Button } from 'ant-design-vue'
import FormLoading from '@/components/FormLoading'
import { deleteInvalidChildren } from '@/utils/index'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  name: 'OperateForm',
  components: {
    ACascader: Cascader,
    AButton: Button,
    AUpload: Upload,
    AModal: Modal,
    AIcon: Icon,
    FormLoading,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    ARow: Row,
    ACol: Col,
    AInput: Input,
    ASelect: Select,
    ASelectOption: Select.Option,
    ATree: Tree
  },
  props: {
    optType: {
      type: String,
      default: 'add'
    }
    // 新增和编辑 optType edit 查看view
  },
  data () {
    return {
      // eslint-disable-next-line no-undef
      map: null,
      // 选额==选择国民经济分类的弹窗
      operateVisible: false,
      modalConfirmLoading: false,
      industryTreeData: [],
      // 国民经济分类的文字
      industryCategoryName: '',
      // 保存选择的行业对象 判断是否第四级国民经济分类
      currentIndustry: {},
      replaceFields: {
        children: 'children',
        title: 'label',
        key: 'id'
      },
      // 标题
      title: '',
      // 提交按钮loading状态
      confirmLoading: false,
      // 表单加载loading
      formLoadingVisible: false,
      enterpriseTypeConst: [],
      industryCodeConst: [],
      industryTypeConst: [],
      industryCategoryConst: [],
      industryBigCategoryConst: [],
      indicatorsGradingConst: [],
      polluteTypeConst: [],
      areaConst: [],
      statusConst: [],
      dataSourcesConst: [
        { id: 1, value: '1', name: '国网侧' },
        { id: 2, value: '2', name: '设备侧' },
        { id: 3, value: '3', name: '固定污染侧' }
      ],
      environmentalProtectionConst: [
        { id: 1, value: '1', name: '污水' },
        { id: 2, value: '2', name: '污土' },
        { id: 3, value: '3', name: '污气' }
      ],
      isOrNotConst: [
        { id: 1, value: '1', name: '是' },
        { id: 2, value: '2', name: '否' }
      ],
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      // 表单
      form: {
        important: 1,
        businessAddress: '',
        latitude: '',
        longitude: '',
        // 国民经济分类的最后一级编码
        industryClassification: '',
        areaList: [],
        fileList: [],
        type: undefined
      },
      rules: {
        flieNo: [
          {
            pattern: regexConstants.codeNum,
            validator: validators.validate,
            message: '只能输入字母、数字',
            trigger: 'change'
          }
        ],
        contacts: [
          {
            validator: validators.validatorEmoji,
            message: '请输入合法的字符',
            trigger: 'change'
          }
        ],
        businessAddress: [
          {
            validator: validators.validatorEmoji,
            message: '请输入合法的字符',
            trigger: 'change'
          }
        ],
        type: [
          { required: true, message: '请选择重点监管企业', trigger: 'change' }
        ],
        areaList: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入企业名称', trigger: 'change' },
          {
            pattern: regexConstants.name,
            validator: validators.validate,
            message: '只能输入汉字、数字、字母',
            trigger: 'change'
          }
        ],
        custUniformCode: [
          { required: true, message: '请输入社会信用代码', trigger: 'change' },
          {
            pattern: regexConstants.custUniformCode,
            validator: validators.validate,
            message: '只能输入字母、数字、下划线、不能以下划线开头、长度18位',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              console.log('触发checkCustUniformCode...')
              if (!this.form.custUniformCode) {
                return callback(new Error(this.rules.custUniformCode[0].message))
              } else if (
                !regexConstants.custUniformCode.test(
                  this.form.custUniformCode
                )
              ) {
                return callback(new Error(this.rules.custUniformCode[1].message))
              }
              const params = { custUniformCode: this.form.custUniformCode }
              if (this.$route.query.id) {
                params.id = this.$route.query.id || ''
              }
              checkCustUniformCode(params).then((res) => {
                if (res.code === '0') {
                  callback()
                } else {
                  callback(new Error(res.msg))
                }
              }).catch(() => {
                callback(new Error('检查社会信用代码失败'))
              })
            },
            trigger: 'change'
          }
        ],
        contactsPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          {
            pattern: regexConstants.contactsPhone,
            validator: validators.validate,
            message: '请输入合法的联系电话',
            trigger: 'change'
          }
        ],
        fileList: [
          { required: true, message: '请上传附件', trigger: 'blur' }
        ]
      },
      previewVisible: false,
      previewImage: '',
      listWorkshop: []
    }
  },
  watch: {
    // 监听抽屉打开关闭
    operateVisible: {
      handler (newV, oldV) {
        // 打开抽屉
        if (newV) {
          // 新增
          if (this.optType === 'add') {
            this.title = '新增企业信息'
          }
          // 编辑
          if (this.optType === 'edit') {
            this.title = '编辑企业信息'
          }
        }
      }
    }
  },
  created () {
  },
  mounted () {
    // eslint-disable-next-line no-undef
    if (this.optType !== 'add') { // 编辑 查看
      this.getinfoById()
    } else { // 增加
      this.getDictDataList()
      this.getIndustry()
      this.loadDefaultmap()
    }
  },
  methods: {
    // 转换数据字典
    convertConstName,
    // 获取地图
    loadmap (query) {
      // eslint-disable-next-line no-undef
      this.map = new T.Map('mapDiv')
      // eslint-disable-next-line no-undef
      var lnglat = new T.LngLat(query.lon, query.lat)
      this.map.centerAndZoom(lnglat, 12)
      const lnglatObj = {
        lng: query.lon,
        lat: query.lat
      }
      const that = this
      // 创建标注工具对象
      // eslint-disable-next-line no-undef
      var lo = new T.Geolocation()
      function fn (e) {
        if (this.getStatus() === 0) {
          that.map.centerAndZoom(lnglatObj, 15)
          // eslint-disable-next-line no-undef
          var marker = new T.Marker(lnglatObj)
          that.map.addOverLay(marker)
        }
        if (this.getStatus() === 1) {
          that.map.centerAndZoom(lnglatObj, e.level)
          // eslint-disable-next-line no-undef
          var marker1 = new T.Marker(lnglatObj)
          that.map.addOverLay(marker1)
        }
      }
      lo.getCurrentPosition(fn)
    },
    // 获取默认地图
    loadDefaultmap () {
      // eslint-disable-next-line no-undef
      this.map = new T.Map('mapDiv')
      // eslint-disable-next-line no-undef
      var lnglat = new T.LngLat(104.07, 30.67)
      this.map.centerAndZoom(lnglat, 12)
      // 创建标注工具对象
      // eslint-disable-next-line no-undef
      var lo = new T.Geolocation()
      const that = this
      function fn (e) {
        if (this.getStatus() === 0) {
          that.map.centerAndZoom(e.lnglat, 15)
          // eslint-disable-next-line no-undef
          var marker = new T.Marker(e.lnglat)
          that.map.addOverLay(marker)
        }
        if (this.getStatus() === 1) {
          that.map.centerAndZoom(e.lnglat, e.level)
          // eslint-disable-next-line no-undef
          // 默认地图不添加marker
          // var marker1 = new T.Marker(e.lnglat)
          // that.map.addOverLay(marker1)
        }
      }
      lo.getCurrentPosition(fn)
    },
    // 定位经纬度和具体地址
    getAdressByKeyWord: debounce(function () {
      // 节流
      const params = {
        place: this.form.businessAddress
      }
      if (this.form.businessAddress !== '') {
        getMapLonAndLatInfo(params).then((res) => {
          if (res.data) {
            this.form.latitude = res.data.lat
            this.form.longitude = res.data.lon
            this.loadmap(res.data)
          }
        })
      }
    }, 1000),
    displayRender ({ labels }) {
      return labels[labels.length - 1]
    },
    // 获取国民经济行业分类
    getIndustry () {
      queryIndustry().then((res) => {
        if (res.data) {
          const data = res.data
          if (Array.isArray(data) && data[0] && Array.isArray(data[0].children)) {
            this.industryTreeData = data[0].children
          } else {
            this.industryTreeData = []
          }
        }
      })
    },
    // 禁止粘贴国民经济行业分类
    handlePaste () {
      return false
    },
    // 打开国民经济行业分类弹窗
    openModalTree () {
      if (this.industryTreeData.length === 0) {
        this.$message.info('正在加载国民经济行业分类！')
      } else {
        this.operateVisible = true
      }
    },
    // 点击行业树状图
    selectIndustry (selectedKeys, info) {
      this.currentIndustry = Object.assign({}, info.node.dataRef)
    },
    // 保存所选的行业
    saveIndustry () {
      // 选择到第四级末端
      if (this.currentIndustry.num !== 4) {
        this.$message.info('请选择国民经济行业的最小分类！')
      } else {
        this.form.industryClassification = this.currentIndustry.id
        this.industryCategoryName = this.currentIndustry.label
        this.form.industryCategoryName = this.currentIndustry.label
        this.operateVisible = false
        // 让输入框失去焦点
        setTimeout(() => {
          this.$refs.industryCategoryRef.blur()
        }, 200)
      }
    },
    // 取消保存的行业
    cancelSaveIndustry () {
      this.operateVisible = false
      // 让输入框失去焦点
      setTimeout(() => {
        this.$refs.industryCategoryRef.blur()
      }, 200)
    },
    // 获取数据字典
    async getDictDataList () {
      const params = 'w-001,Y-0B-003,Y-0B-004,Y-0B-005,Y-0B-006,Y-0B-007,Y-0B-008,Y-002,Y-0B-009,Y-0B-010,Y-0B-011'
      // 省市区
      const tegionInfo = await getInfo('Y-001')
      if (tegionInfo.code === '0') {
        this.areaConst = deleteInvalidChildren(tegionInfo.data)
      }
      getDictData(params).then((res) => {
        if (res.code === '0') {
          const data = res.data
          // 行业门类
          this.industryCategoryConst = data['w-001']
          // 企业类型
          this.enterpriseTypeConst = data['Y-0B-003']
          // 行业代码
          this.industryCodeConst = data['Y-0B-004']
          // 产业类型
          this.industryTypeConst = data['Y-0B-005']
          // 行业大类
          this.industryBigCategoryConst = data['Y-0B-006']
          // 绩效分级指标
          this.indicatorsGradingConst = data['Y-0B-011']
          // 污染类型
          this.polluteTypeConst = data['Y-0B-008']
          this.statusConst = data['Y-002']
          this.dataSourcesConst = data['Y-0B-009']
          this.environmentalProtectionConst = data['Y-0B-010']
        }
      })
    },
    // 切换区域
    areaChange (valueArr, selectedOptions) {
      const length = (selectedOptions && selectedOptions.length) || 0
      // this.form.province = length >= 1 ? selectedOptions[0].title : ''
      // this.form.city = length >= 2 ? selectedOptions[1].title : ''
      // this.form.area = length >= 3 ? selectedOptions[2].title : ''
      // this.form.planTownship = length >= 4 ? selectedOptions[3].title : ''
      // this.form.provinceCode = length >= 1 ? selectedOptions[0].key : ''
      // this.form.cityCode = length >= 2 ? selectedOptions[1].key : ''
      // this.form.areaCode = length >= 3 ? selectedOptions[2].key : ''
      // this.form.planCode = length >= 4 ? selectedOptions[3].key : ''
      if (length) {
        const ids = selectedOptions[length - 1].ids || ''
        const names = selectedOptions[length - 1].names || ''
        const idArr = ids.split(',')
        const nameArr = names.split(',')
        idArr.pop()
        nameArr.pop()
        const index = idArr.findIndex((id) => id === valueArr[length - 1]) // 当前最后一级节点的id在ids的哪一个位置
        if (index > -1) {
          this.form.provinceCode = index >= 0 ? idArr[0] : ''
          this.form.cityCode = index >= 1 ? idArr[1] : ''
          this.form.areaCode = index >= 2 ? idArr[2] : ''
          this.form.planCode = index >= 3 ? idArr[3] : ''
          this.form.province = index >= 0 ? nameArr[0] : ''
          this.form.city = index >= 1 ? nameArr[1] : ''
          this.form.area = index >= 2 ? nameArr[2] : ''
          this.form.planTownship = index >= 3 ? nameArr[3] : ''
        }
      }
    },
    async getinfoById () {
      this.formLoadingVisible = true
      const params = {
        id: this.$route.query.id
      }
      const query = 'w-001,Y-0B-003,Y-0B-004,Y-0B-005,Y-0B-006,Y-0B-007,Y-0B-008,Y-002,Y-0B-009,Y-0B-010,Y-0B-011'
      // 省市区
      const getTegionInfoPromise = async () => {
        const tegionInfo = await getInfo('Y-001')
        if (tegionInfo.code === '0') {
          this.areaConst = deleteInvalidChildren(tegionInfo.data)
        }
      }
      const queryIndustryPromise = async () => {
        const industryTreeData = await queryIndustry()
        if (Array.isArray(industryTreeData.data) && industryTreeData.data[0] && Array.isArray(industryTreeData.data[0].children)) {
          this.industryTreeData = industryTreeData.data[0].children
        } else {
          this.industryTreeData = []
        }
      }
      const getHnEntinfoByIdPromise = async () => {
        await getDictData(query).then(async (res) => {
          if (res.code === '0') {
            const data = res.data
            // 行业门类
            this.industryCategoryConst = data['w-001']
            // 企业类型
            this.enterpriseTypeConst = data['Y-0B-003']
            // 行业代码
            this.industryCodeConst = data['Y-0B-004']
            // 产业类型
            this.industryTypeConst = data['Y-0B-005']
            // 行业大类
            this.industryBigCategoryConst = data['Y-0B-006']
            // 绩效分级指标
            this.indicatorsGradingConst = data['Y-0B-011']
            // 污染类型
            this.polluteTypeConst = data['Y-0B-008']
            this.statusConst = data['Y-002']
            this.dataSourcesConst = data['Y-0B-009']
            this.environmentalProtectionConst = data['Y-0B-010']
          }
          await getHnEntinfoById(params).then((res) => {
            this.formLoadingVisible = false
            if (res.code === '0') {
              const data = res.data
              const params = {
                lon: data.longitude,
                lat: data.latitude
              }
              setTimeout(() => {
                if (params.lon || params.lat) {
                  this.loadmap(params)
                } else {
                  this.loadDefaultmap()
                }
              }, 100)
              // 将为空的属性转为undefined
              const formObj = {}
              Object.entries(res.data).forEach(([key, value]) => {
                formObj[key] = value || undefined
              })
              this.form = Object.assign({}, formObj)
              if (data.industryCategoryName) {
                this.currentIndustry.id = data.industryCategoryCode
                this.currentIndustry.label = data.industryCategoryName
                this.currentIndustry.num = 4
                this.industryCategoryName = data.industryCategoryName
              }
              const fileList = []
              data.listHnFileInfo && data.listHnFileInfo.forEach((item, index) => {
                fileList.push({
                  fileName: item.fileName,
                  fileUrl: item.fileUrl,
                  url: item.fileUrl,
                  id: item.fileId,
                  uid: item.id,
                  name: item.fileName,
                  status: 'done'
                })
              })
              this.form.fileList = [...fileList]
              // this.form.areaList = [data.provinceCode, data.cityCode]
              // if (data.areaCode) {
              //   this.form.areaList = [data.provinceCode, data.cityCode, data.areaCode]
              // }
              // if (data.planCode) {
              //   this.form.areaList = [data.provinceCode, data.cityCode, data.areaCode, data.planCode]
              // }
              // 判断areaConst是否有这些节点(provinceCode, cityCode, areaCode, planCode) 没有的说明不是有效节点
              let isHaveProvinceCode = false
              let isHaveCityCode = false
              let isHaveAreaCode = false
              let isHavePlanCode = false
              const { provinceCode, cityCode, areaCode, planCode } = data
              const fnc = (treeData) => {
                treeData.forEach((p) => {
                  if (p.key === provinceCode) {
                    isHaveProvinceCode = true
                  }
                  if (p.key === cityCode) {
                    isHaveCityCode = true
                  }
                  if (p.key === areaCode) {
                    isHaveAreaCode = true
                  }
                  if (p.key === planCode) {
                    isHavePlanCode = true
                  }
                  if (p.children && p.children.length) {
                    fnc(p.children)
                  }
                })
              }
              fnc(this.areaConst)
              this.form.areaList = []
              if (isHaveProvinceCode) {
                this.form.areaList.push(provinceCode)
              }
              if (isHaveCityCode) {
                this.form.areaList.push(cityCode)
              }
              if (isHaveAreaCode) {
                this.form.areaList.push(areaCode)
              }
              if (isHavePlanCode) {
                this.form.areaList.push(planCode)
              }
            }
          }).catch(() => {
          })
        }).catch(() => {
        })
      }
      await Promise.all([getTegionInfoPromise(), queryIndustryPromise(), getHnEntinfoByIdPromise()])
    },
    // 新增或者修改
    saveInfo () {
      this.confirmLoading = true
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const form = { ...this.form }
          const listHnFileInfo = []
          form.fileList.forEach((item, index) => {
            listHnFileInfo.push({
              fileName: item.fileName,
              fileUrl: item.fileUrl,
              id: item.id
            })
          })
          delete form.areaList
          delete form.fileList
          const params = Object.assign({}, form, {
            listHnFileInfo: listHnFileInfo
          })
          for (const key in params) {
            if (params[key] === undefined) {
              params[key] = ''
            }
          }
          if (this.optType === 'add') {
            await addEntinfo(params).then((res) => {
              if (res.code === '0') {
                this.$message.success('保存成功!')
                this.$router.push('/enterpriseInformationManagement/enterpriseInformation')
              }
            }).catch(() => {
            })
          } else {
            params.id = this.$route.query.id
            await updateEntinfo(params).then((res) => {
              if (res.code === '0') {
                this.$message.success('保存成功!')
                this.$router.push('/enterpriseInformationManagement/enterpriseInformation')
              }
            }).catch(() => {
            })
            this.confirmLoading = false
          }
        } else {
          this.confirmLoading = false
          this.$message.error('请完善信息！')
          return false
        }
      })
    },
    // 关闭抽屉
    cancleSave () {
      this.$router.push('/enterpriseInformationManagement/enterpriseInformation')
    },
    // 切换性别
    sexChange () {
    },
    handleCancel () {
      this.previewVisible = false
    },
    // 预览上传的图片
    async handlePreview (file) {
      if (!file.fileUrl && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.fileUrl || file.preview
      this.previewVisible = true
    },
    // 本地移除上传文件
    handleRemove (file) {
      if (this.optType === 'view') {
        return false
      }
      const index = this.form.fileList.indexOf(file)
      const newFileList = this.form.fileList.slice()
      newFileList.splice(index, 1)
      this.form.fileList = [...newFileList]
      this.$forceUpdate()
    },
    // 上传文件之前校验
    beforeUpload (file) {
      // this.form.fileList = [...this.form.fileList, file]
      const isImage =
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 <= 10
      if (!isImage) {
        this.$message.error('附件只能是png,jpg,jpeg格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('附件大小不能超过 10M!')
        return false
      }
      const formData = new FormData()
      formData.append('file', file)
      formData.append('path', '/file/customer')
      // this.uploading = true
      const url = '/ycloud-file-center/file/upload'
      const requestConfig = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      return new Promise((resolve, reject) => {
        post(url, formData, requestConfig).then((res) => {
          if (res.code === '0') {
            const data = res.data
            this.form.fileList.push({
              fileName: data.fileName,
              fileUrl: data.url,
              url: data.url,
              id: data.fileId,
              uid: data.id,
              name: data.fileName,
              status: 'done'
            })
          } else {
            reject(res.mag)
          }
        }).catch((error) => {
          reject(error)
        })
      })
    }
  }
}
</script>
<style lang="scss">
.upload-label {
  .ant-form-explain {
    display: none;
  }
}
.industryTreeModal {
  z-index: 999999;
}
.form-title {
  font-size: 16px;
  border-bottom: 1px solid #e8e8e8;
  height: 40px;
  margin-bottom: 20px;
}
.tian-map {
  width: 100%;
  height: 400px;
  margin: 0 0 20px 0;
  // background: #cccccc;
}
.operate-form-enterpriseInformation {
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  .line-table {
    th {
      height: 50px;
    }
    td {
      height: 50px;
    }
  }
}
.opreate-add {
  width: 100%;
  text-align: center;
}
.opreate-buttons {
  width: 100%;
  text-align: center;
  margin-top: 20px;
}
</style>
